<script setup lang="ts">
  import { PropType, ref } from 'vue'
  import AMapLoader from '@amap/amap-jsapi-loader'
  import mapConfig from '@/config/map'
  import '@amap/amap-jsapi-types'
  import positionImg from '@/assets/image/pages/home/position.png'

  defineOptions({
    name: 'MapHome',
  })

  const props = defineProps({
    mode: {
      type: String as PropType<'mini' | 'fullScreen'>,
      default: () => 'mini',
    },
  })

  // 地图配置
  const mapOptions: AMap.MapOptions = {
    center: [104.041098, 30.690683],
    zoom: props.mode === 'mini' ? 3 : 4.3,
    viewMode: '2D',
    showBuildingBlock: true,
  }

  // 地图加载
  const mapLoading = ref(false)

  // 地图组件实例
  const mapInstance = ref<AMap.Map>(null)

  // 需要标注的地址列表
  const addressList = ref([
    '广东省中山市东凤镇和穗湿地公园',
    '广东省小榄海港中心写字楼',
    '广东省中山纪念中学',
    '广东省中山市技师学院东校区',
    '广东省广州北京路',
    '广东省博物馆',
    '广东省广州市猎德大桥',
    '广东省深圳市世界之窗',
    '广东省佛山市顺德市华侨城',
    '广东省广州市广州动物园',
    '广东省广州市人民政府',
  ])

  const createTagInfo = (content: string, marker: AMap.Marker) => {
    const homeMapTagWindow = document.createElement('div')
    homeMapTagWindow.style.width = '300px'
    homeMapTagWindow.style.background = '#fff'
    homeMapTagWindow.style.borderRadius = '3px'
    homeMapTagWindow.style.padding = '12px'
    homeMapTagWindow.style.boxShadow = '0 2px 6px 0 rgba(114, 124, 246, 0.5)'
    homeMapTagWindow.style.position = 'relative'
    homeMapTagWindow.style.transform = 'translate(0, -20px)'

    const homeMapTagSharp = document.createElement('div')
    homeMapTagSharp.style.position = 'absolute'
    homeMapTagSharp.style.bottom = '0'
    homeMapTagSharp.style.left = '50%'
    homeMapTagSharp.style.marginLeft = '-8px'
    homeMapTagSharp.style.borderLeft = '8px solid transparent'
    homeMapTagSharp.style.borderRight = '8px solid transparent'
    homeMapTagSharp.style.borderTop = '8px solid #fff'
    homeMapTagSharp.style.transform = 'translate(0, 100%)'

    const header = document.createElement('div')
    header.style.display = 'flex'
    header.style.justifyContent = 'space-between'

    const divider = document.createElement('div')
    divider.style.borderBottom = '1px dotted #e5e5e5'
    divider.style.width = '100%'
    divider.style.margin = '12px 0'

    const title = document.createElement('div')
    title.innerText = '标题'
    title.style.color = '#606266'

    const icon = document.createElement('i')
    icon.className = 'iconfont icon-guanbi'
    icon.onclick = () => {
      if (mapInstance.value) {
        mapInstance.value.remove(marker)
      }
    }

    const contentDiv = document.createElement('div')
    contentDiv.innerText = content
    contentDiv.style.fontSize = '14px'

    homeMapTagWindow.appendChild(homeMapTagSharp)
    header.appendChild(title)
    header.appendChild(icon)
    homeMapTagWindow.appendChild(header)
    homeMapTagWindow.appendChild(divider)
    homeMapTagWindow.appendChild(contentDiv)
    return homeMapTagWindow
  }

  /**
   * 添加标志
   * @param {Object} AMap - 地图类
   */
  const mapAddressList = (AMap: any) => {
    // 注册地理序列号插件
    AMap.plugin('AMap.Geocoder', function () {
      // 实例化地理序列号
      const geocoder = new AMap.Geocoder()

      // 将地址转换为经纬度
      geocoder.getLocation(addressList.value, function (status, result) {
        // 转换成功
        if (status === 'complete' && result.info === 'OK') {
          // 创建文字图层
          const labelsLayer: AMap.LabelsLayer = new AMap.LabelsLayer({
            collision: true,
          })

          // 标记集合
          const labelMarkers: Array<AMap.LabelMarker> = []

          // 标记
          const marker: AMap.Marker = new AMap.Marker({
            anchor: 'bottom-center',
            offset: [0, -15],
          })

          // 遍历经纬度集合
          result.geocodes.forEach((item) => {
            const labelMarker: AMap.LabelMarker = new AMap.LabelMarker({
              position: [item.location.lng, item.location.lat],
              icon: {
                image: positionImg,
                anchor: 'bottom-center',
                size: [18, 27],
              },
            })

            labelMarkers.push(labelMarker)

            /**
             * 监听标记的鼠标移入事件
             */
            labelMarker.on('click', () => {
              marker.setContent(createTagInfo(item.formattedAddress, marker))
              marker.setPosition([item.location.lng, item.location.lat])
              mapInstance.value.add(marker)
            })
          })

          // 将标记添加到文字图层上
          labelsLayer.add(labelMarkers)

          // 将文字图层添加到地图上
          mapInstance.value.add(labelsLayer)
        }
      })
    })
  }

  defineExpose({
    install: () => {
      mapLoading.value = true
      window._AMapSecurityConfig = {
        securityJsCode: mapConfig.securityJsCode,
      }
      AMapLoader.load({
        key: mapConfig.key,
        version: '2.0',
        plugins: ['AMap.Scale'],
      }).then((AMap) => {
        mapInstance.value = new AMap.Map('homeMap', mapOptions)
        mapAddressList(AMap)
        mapLoading.value = false
      })
    },
    destory: () => {
      if (mapInstance.value) {
        mapInstance.value.destroy()
        mapInstance.value = null
      }
    },
  })
</script>

<template>
  <div id="homeMap" v-loading="mapLoading"></div>
</template>

<style scoped lang="scss">
  #homeMap {
    width: 100%;
    height: 100%;
  }
</style>
